package com.yd.mvc.baseController;

import com.yd.app.util.BusinessException;
import com.yd.app.util.SystemException;
import com.yd.mvc.baseController.util.ExceptionHandlerCallback;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class BaseExController {

    //登录controller地址
    private String loginViewUrl="/user/login/index";
    @Autowired
    private ExceptionHandlerCallback exceptionHandlerCallback;
    private String errorPage="500";
    /**
     * 用于处理跳转页面的controller出现的异常
     * @param request
     * @param response
     * @param ex
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public String exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception ex){
        System.out.println("异常拦截");
        if (ex instanceof BusinessException) {
            request.setAttribute("message", ex.getMessage());
            //如果是未登录，则跳转到登陆页面
            if("no-login".equals(((BusinessException) ex).getType())){
                String contextPath=request.getServletContext().getContextPath();
                String requestUri=request.getRequestURI();
                if(!StringUtils.isEmpty(contextPath)){
                    requestUri=requestUri.substring(contextPath.length());
                }
                return "redirect:"+loginViewUrl+"?ref="+requestUri;
            }
        }else if(ex instanceof SystemException) {
            request.setAttribute("message", ex.getMessage());
        } else {
            request.setAttribute("message", "系统繁忙，请稍后重试！！");
        }
        exceptionHandlerCallback.callback(request,response,null,ex);
        return errorPage;
    }
}
